package com.bhatni.taskmanager.task;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFileTask extends TaskBase {

    private String sourceLocation;
    private String destinationLocation;

    public CopyFileTask() {
    }
    

    public void run() {
        File src = new File(this.getSourceLocation());
        File dest = new File(this.getDestinationLocation());
        FileInputStream fis;
        try {
            fis = new FileInputStream(src);
        } catch (IOException e) {
            System.out.println("ERROR: File not found : " + this.getSourceLocation());
            return;
        }
        File dir = new File(dest.getParent());
        if (!dir.exists()) {
            dir.mkdirs();
        }
        if (!dir.exists()) {
            System.out.println("ERROR: Unable to create directory "
                    + dest.getParent());
            return;
        }
        try {
            FileOutputStream fos = null;
            if (dest.exists()) {
                String filename = dest.getName();
                int index = filename.lastIndexOf('.');
                File tmp;

                if (index >= 0) {
                    tmp = File.createTempFile(filename.substring(0, index)
                            + "~", filename.substring(index), dir);
                } else {
                    tmp = File.createTempFile(filename, "", dir);
                }
                fos = new FileOutputStream(tmp);
            } else {
                fos = new FileOutputStream(dest);
            }
            byte[] buf = new byte[1024];
            int i = 0;
            while ((i = fis.read(buf)) != -1) {
                fos.write(buf, 0, i);
            }
            fis.close();
            fos.close();
        } catch (IOException e) {
            System.out.println("ERROR: Copy failed for file " + this.getSourceLocation());
        }
    }

    /**
     * @return the sourceLocation
     */
    public String getSourceLocation() {
        return sourceLocation;
    }

    /**
     * @param sourceLocation the sourceLocation to set
     */
    public void setSourceLocation(String sourceLocation) {
        this.sourceLocation = sourceLocation;
    }

    /**
     * @return the destinationLocation
     */
    public String getDestinationLocation() {
        return destinationLocation;
    }

    /**
     * @param destinationLocation the destinationLocation to set
     */
    public void setDestinationLocation(String destinationLocation) {
        this.destinationLocation = destinationLocation;
    }
}
